﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace NLUNZ.UserControls
{
    public partial class TrackingSearchResults : System.Web.UI.UserControl
    {
        private List<TrackingItem> _items; 
        protected void Page_Load(object sender, EventArgs e)
        {
            //if postback is true, check data in input textbox
            //if postback is false, check data in querystring
            //on load, retrieve the delivery object from LINQ
            //data binding to TrackingItem

            EmptyResult.Visible = false;
            List<string> keys = Page.IsPostBack ? GetKeysFromInput() : GetKeysFromQueryString();
            List<string> searchKeys = TrimResultList(keys);
            if(searchKeys.Count !=0)
            {
                _items = GetItemsByKeys(searchKeys);
                DataBindTrackingView(_items);
            }
            ClientScriptManager csm = Page.ClientScript;
            string scriptKey = "searchResultFormatting";
            if(!csm.IsClientScriptBlockRegistered("searchResultFormatting"))
            {
                string script = getScript();
                csm.RegisterClientScriptBlock(this.GetType(),scriptKey,script);
            }
        }

        private string getScript()
        {
            StringBuilder script = new StringBuilder();
            script.Append(
                "<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>");
            script.Append("<script type=\"text/javascript\">$(document).ready(function () {");
            //script.Append("$(\"table.tracking-result-table tr:even\").css(\"background-color\", \"#cccccc\");");
            script.Append("$(\"#tracking-result-area .tracking-datetime:contains('LOADING')\").each(function () {");
            script.Append(" var parentTd = $(this).parent();");
            script.Append("var trackingId = $(\".tracking-description\", parentTd).html();");
            script.Append(
                "$(this).parent().after('<tr id=\"'+trackingId+'\"><td colspan=\"2\">Loading...<img src=\"/Images/ajax-loader.gif\" /></td>');");
            script.Append("parentTd.remove();");
            //script.Append("$(this).parent().after('<tr id=><td colspan=\"2\">Loading...<img src=\"/Images/ajax-loader.gif\" /></td>');");
            script.Append("});");

            //script for loadTrackingData
            script.Append(
                " var loadTrackingData = function(tn){ return function (msg) { var data = jQuery.parseJSON(msg.d); var returnHtml = ''; var len = data.data.length; jQuery.each(data.data, function (rec)");
            script.Append(
                " { returnHtml += \"<tr class='tracking-row\"; if(rec==len-1) returnHtml += \" tracking-row-highlighted \"; returnHtml += \"'><td class='tracking-datetime'>\" + this.time + \"</td><td class='tracking-description'>\" + this.context + \"</td></tr>\";}); ");
            script.Append("var trackingSectionId = \"#\" + tn; var loadingSection = $(trackingSectionId); loadingSection.after(returnHtml); loadingSection.remove();  }; };");

            string webServiceUrl = ConfigurationManager.AppSettings["webServiceUrl"]; //"TrackingService.asmx/FindTracking"
            if(_items != null)
            {
                foreach (TrackingItem item in _items)
                {
                    foreach (CourierTracking courier in item.CourierTrackings)
                    {
                        script.Append(" $.ajax({ type: \"POST\", url: \""+webServiceUrl+"\",");
                        script.Append(
                            "data: '{code: \"" + courier.CourierTrackingCode + "\", trackingNumber: \""+ courier.CourierTrackingNumber+"\"}',");
                        script.Append(
                            "contentType: \"application/json; charset=utf-8\", dataType: \"json\", success: loadTrackingData(" +
                            courier.CourierTrackingNumber + "),");
                        script.Append("error: function (msg) { alert(\"ERROR\");} });");
                    }
                }                
            }


            //script.Append("};");


            script.Append("});</script>");
            return script.ToString();
        }

        private List<string> TrimResultList(List<string> keys)
        {
            List<string> result = new List<string>();
            foreach (string key in keys)
            {
                if(key.Trim().Length > 0)
                    result.Add(key.Trim());
            }
            return result;
        }

        private void DataBindTrackingView(List<TrackingItem> items)
        {
            DataTable trackingNumbers = LoadTrackingNumbers(items);
            rptSearchResults.DataSource = trackingNumbers;
            rptSearchResults.DataBind();


            if (items.Count == 0)
            {
                EmptyResult.Visible = true;
            }
        }

        private DataTable LoadTrackingNumbers(List<TrackingItem> items)
        {
            var table = new DataTable();
            table.Columns.Add("DeliveryNumber", typeof(string));
            foreach (TrackingItem item in items)
            {
                table.Rows.Add(item.TIDeliveryNumber);
            }
            return table;
        }

        private DataTable LoadItemToTable(string deliveryNumber)
        {
            TrackingItem trackingItem = new TrackingItem();
            foreach (TrackingItem item in _items)
            {
                if (item.TIDeliveryNumber == deliveryNumber)
                    trackingItem = item;
            }

            DataTable table = CreateTrackingDataTable();
            if(trackingItem.PickupDateTime != DateTime.MinValue)
            {
                table.Rows.Add(trackingItem.PickupDateTime.ToString("yyyy-MM-dd HH:ss:mm"), trackingItem.TIPickupBy);
                if(trackingItem.InventoryDateTime != DateTime.MinValue)
                {
                    table.Rows.Add(trackingItem.InventoryDateTime.ToString("yyyy-MM-dd HH:ss:mm"), trackingItem.InventoryDescription);
                }
                if(trackingItem.ArrivalDepartureAirportDateTime != DateTime.MinValue)
                {
                    table.Rows.Add(trackingItem.ArrivalDepartureAirportDateTime.ToString("yyyy-MM-dd HH:ss:mm"),
                                    trackingItem.ArrivalDepartureAirportDescription);
                }
            }
            if(trackingItem.DeliveryToDestinationCountryCustomDateTime != DateTime.MinValue)
            {
                table.Rows.Add(trackingItem.DeliveryToDestinationCountryCustomDateTime.ToString("yyyy-MM-dd HH:ss:mm"),
                                trackingItem.DeliveryToDestinationCountryCustom);
                if(IsDateExpired(trackingItem.ArrivalDestinationCountryCustomDateTime))
                {
                    table.Rows.Add(trackingItem.ArrivalDestinationCountryCustomDateTime.ToString("yyyy-MM-dd HH:ss:mm"),
                                    trackingItem.ArrivalDestinationCountryCustom);
                }
                if(IsDateExpired(trackingItem.ArrivalDestinationCountryCustomDateTime) && trackingItem.ClearCustomDateTime != DateTime.MinValue)
                {
                    table.Rows.Add(trackingItem.ClearCustomDateTime.ToString("yyyy-MM-dd HH:ss:mm"), trackingItem.ClearCustom);
                }
                //check if courier in destination is available
                if(trackingItem.CourierTrackings.Count > 0)
                {
                    int count = 0;
                    int total = trackingItem.CourierTrackings.Count;
                    foreach (CourierTracking courierTracking in trackingItem.CourierTrackings)
                    {
                        count++;
                        string subTitle = String.Format("快件{2} of {3} 抵达 <b>{0}</b>, 跟踪号码为 [<b>{1}</b>]",
                                                        courierTracking.CourierCompanyName,
                                                        courierTracking.CourierTrackingNumber,
                                                        count,
                                                        total);
                        table.Rows.Add(courierTracking.CourierDateTime, subTitle);
                        table.Rows.Add("LOADING",courierTracking.CourierTrackingNumber);

                        //1. register script block
                        //2. make call to 
                        //if(!String.IsNullOrEmpty(courierTracking.TrackingXML))
                        //{
                        //    if(!courierTracking.TrackingXML.StartsWith("ERROR"))
                        //    {
                        //         List<Dictionary> xmlTracking = LoadXMLToList(courierTracking.TrackingXML);
                        //        if(xmlTracking.Count > 0)
                        //        {
                        //            foreach (Dictionary dictionary in xmlTracking)
                        //            {
                        //                table.Rows.Add(dictionary.Key,dictionary.Value);
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        table.Rows.Add("", string.Format("<b>{0}</b>", courierTracking.TrackingXML));
                        //    }                    

                        //}

                    }
                }
            }
            return table;
        }

        /*
        private List<Dictionary> LoadXMLToList(string trackingXml)
        {
            List<Dictionary> result = new List<Dictionary>();
            XmlDocument document = new XmlDocument();
            document.LoadXml(trackingXml);
            XmlElement root = document.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("/xml/data");

            if(nodes != null)
            {
                foreach (XmlNode node in nodes)
                {
                    string time = node.FirstChild.InnerText;
                    string track = node.LastChild.InnerText;
                    if(!String.IsNullOrEmpty(time))
                    {
                        result.Add(new Dictionary(){Key=time,Value = track});
                    }
                }
            }
            return result;
        }
         * */

        private bool IsDateExpired(DateTime arrivalDestinationCountryCustomDateTime)
        {
            DateTime dtNow = DateTime.UtcNow.AddHours(12);
            if (dtNow > arrivalDestinationCountryCustomDateTime)
                return true;
            return false;
        }

        private DataTable CreateTrackingDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("TrackingDateTime", typeof(string));
            table.Columns.Add("TrackingDescription", typeof(string));

            return table;
        }

        private List<TrackingItem> GetItemsByKeys(List<string> searchKeys)
        {
            List<Delivery> deliveries = Repository.GetDeliveryById(searchKeys);
            List<TrackingItem> items = new List<TrackingItem>();
            foreach (Delivery delivery in deliveries)
            {
                items.Add(Repository.DeliveryTrackingItemMapping(delivery));
            }
            return items;
        }



        private List<string> GetKeysFromQueryString()
        {
            string queryString = Request.QueryString["keys"] == null ? string.Empty : Request.QueryString["keys"].ToString(CultureInfo.InvariantCulture);
            List<string> keys = Regex.Split(queryString, ",").ToList();
            string inputData = string.Empty;
                for (int i = 0; i < keys.Count;i++)
                {
                    if(i == keys.Count -1)
                        inputData += keys[i];
                    else
                        inputData += keys[i] + "\r\n";
                }
            txtSearchInput.Text = inputData;
            return keys;
        }

        private List<string> GetKeysFromInput()
        {
            string input = txtSearchInput.Text;
            List<string> searchKeys = Regex.Split(input, "\r\n").ToList();
            return searchKeys;
        }
        public struct ResultSet
        {
            public DateTime StatusDate;
            public string StatusDescription;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

        }

        protected void rptSearchResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblSearchNumber = (Label) e.Item.FindControl("lblSearchNumber");

            string deliveryNumber = lblSearchNumber.Text;

            DataTable table = LoadItemToTable(deliveryNumber);

            ListView listView = new ListView();
            listView = (ListView) e.Item.FindControl("searchItem");
            listView.DataSource = table;
            listView.DataBind();
        }
    }
}